package com.danciyixue.boot.core.security.service;

import com.danciyixue.boot.dcyx.model.entity.DcyxUsers;
import com.danciyixue.boot.dcyx.service.DcyxUsersService;
import com.danciyixue.boot.core.security.model.ClientUserDetails;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
/**
 * 客户端用户详情服务实现类
 */
@Service("clientUserDetailsService")
@RequiredArgsConstructor
@Slf4j
public class ClientUserDetailsService implements UserDetailsService {

    private final DcyxUsersService dcyxUsersService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {

            // 查询用户信息
            DcyxUsers user = dcyxUsersService.getByUsername(username);
            if (user == null) {
                throw new UsernameNotFoundException("用户不存在");
            }
            
            // 检查用户状态
            if (user.getStatus() != null && user.getStatus() == 0) {
                throw new UsernameNotFoundException("用户已被禁用");
            }
            
            // 创建ClientUserDetails对象
            return new ClientUserDetails(
                user.getId(),
                user.getUsername(),
                user.getPassword(),
                user.getStatus() == 1
                );
            }
            catch (Exception e) {
                            // 记录异常日志
            log.error("认证异常:{}", e.getMessage());
                throw e;
            }
    }
} 